import React from 'react'
import { notification, Layout, Modal, Form, Input, Button, Col, Icon, Message,Steps} from 'antd';
import api from '../../../api/resetmailbox';
const { Header, Footer, Sider, Content } = Layout;
import { withRouter, Link } from 'react-router-dom';
const urlTools = require('url');
const FormItem = Form.Item;
const Step = Steps.Step;


import PanelBox from '../../../components/PanelBox';

import './index.less'
import { Row } from 'antd/lib/grid';

    const steps = [{
      title: '第一步',
      content: '输入旧邮箱',
    }, {
      title: '第二步',
      content: '输入新邮箱',
    }, {
      title: '第三步',
      content: '完成',
    }];

class ManageForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      current: 0,
      disabledMailSend: false,
      bindtoken:null,
      sendcode: '发送验证码'
    };
  }
  next() {
    const email =  this.props.form;
      if (email.getFieldValue('used')==null) {
        Message.warning("请输入您的邮箱");
        return ;
        }
      api.get('/verifyingmailbox', 
      {
        email:email.getFieldValue('used')
      }).then((data) => {
        if (data.data.code == 0) {
           if(this.state.current==0){
            const current = this.state.current + 1;
            this.setState({ current });
           }else{
            Message.error("请勿频繁操作！");
           }
        } else {
          Message.error(data.data.message);
          return ;
        }
      });


    
  }
  prev() {
    const current = this.state.current - 1;
    this.setState({ current });
  }



  
   sendsubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          loading: true
        });
        const formData = this.props.form.getFieldsValue();
        api.post("/sendMailbind", 
        {
            ...values
        }).then((res) => {
          let data = res.data;
          if (data.code == 0) {
            this.props.form.resetFields(["mailCode"]);
            this.props.form.setFields({
              mailCode: {
                value: formData.mailCode
              }
            });
            let i = 60;
            let timer = setInterval(() => {
              this.setState({
                sendcode: i--+"秒后可从新发送"
              });
              if (i == 0) {
                clearInterval(timer);
                this.setState({
                  sendcode: '发送验证码',
                  disabledMailSend: false
                });
              }
            }, 1000);
            Modal.success({
              title: '发送邮件成功',
              content: '请登录你的新邮箱查看验证码.如果没有收到请重新发送'
            });
          } else {
            message.error(data.message);
            if (data.messages) {
              data.messages.forEach(item => {
                var obj = {};
                obj[item.field] = {
                  value: formData[item.field],
                  errors: [new Error(item.error)]
                }
                this.props.form.setFields(obj);
              });
            }
          }
        }).catch((e) => {
          console.error(e);
          console.error(e.response);
          message.error("操作失败,请稍后在试");
        });
      }
    });
  }
 

  /* checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  } */

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }


  submit()  {
    this.props.form.validateFields((err, values) => {
      const formData = this.props.form.getFieldsValue()
      if (!formData.mailCode || formData.mailCode.trim().length == 0) {
        this.props.form.setFields({
          mailCode: {
            value: formData.mailCode,
            errors: [new Error('邮箱验证码不能为空')],
          },
        });
        return;
      }
      if (!formData.mailCode && formData.mailCode.trim().length != 4) {
        this.props.form.setFields({
          mailCode: {
            value: formData.mailCode,
            errors: [new Error('邮箱验证码为4个字符')],
          },
        });
        return;
      }
      if (err) {
        return;
      }
      api.put("/validMailCode", formData).then((res) => {
        let data = res.data;
        if (data.code == 0) {
          Modal.success({
            title: '替换邮件',
            content: '邮箱替换成功！'
          });
          const current = this.state.current + 1;
          this.setState({ current });
        } else {
          message.error(data.message);
          if (data.messages) {
            data.messages.forEach(item => {
              var obj = {};
              obj[item.field] = {
                value: formData[item.field],
                errors: [new Error(item.error)]
              }
              this.props.form.setFields(obj);
            });
          }
        }
      }).catch((e) => {
        console.error(e);
        console.error(e.response);
        message.error("操作失败,请稍后在试");
      });
    });
  }

  mailCodeChange(event) {
    let config = {
      mailCode: {
        value: event.target.value
      }
    }
    if (event.target.value.trim().length != 4) {
      config.mailCode.errors = [new Error("邮箱验证码为4位字符")];
    }
    this.props.form.setFields(config);
  }

  cancelMailModal = () => {
    this.props.cancelMailModal();
  }

  toLogin() {
    this.props.history.replace('/login');
  }

  changeUrl = (url) => {
    let obj = urlTools.parse(url, true);
    let urlPrefix = url.substring(0, url.indexOf("?"));
    return urlPrefix + "?bindToken=" + obj.query.bindToken + "&random=" + Math.ceil(Math.random() * 9000 + 1000);
  }

  changeImage = (event) => {
    this.setState({
      captcha: this.changeUrl(this.state.captcha)
    })
  }

  config = (params = {}) => {
    clearForm: () => {
      this.props.form.resetFields();
    },
      api.get("/getCaptcha").then((res) => {
        let data = res.data;
        if (data.code == 0) {
          this.setState({
            captcha: data.data.imageCaptchaUrl + "&random=" + Math.ceil(Math.random() * 9000 + 1000)
          });
          this.props.form.setFieldsValue({
            imageCaptchaToken: data.data.imageCaptchaToken
          })
        }
      }).catch((e) => {
        message.error("载入失败,请稍后在试");
      });
  }

  componentDidMount = () => {
    this.config();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 9 },
      wrapperCol: { span: 7 },
    };
    const { current } = this.state;
    return (
      <Form onSubmit={this.sendsubmit}>
      <Row>
      <div>
        <Steps current={current}>
          {steps.map(item => <Step key={item.title} title={item.title} />)}
        </Steps>
        <div className="steps-content">
        {getFieldDecorator('imageCaptchaToken', {
            })(
              <Input type="hidden" />
              )}
        {
            this.state.current === steps.length - 3
            &&
            <Col>
            <FormItem
                {...formItemLayout}
                  label="旧邮箱"
                  hasFeedback
            >
            {getFieldDecorator('used', {
                  rules: [{
                            type: 'used', message: '输入的类型错误'
                  }, {
                            required: true, message: '请输入您的旧邮箱'
                  },
                  {
                    validator: this.checkBinding
                  }]
                  })(
                    <Input   type="email" className="content_style" addonBefore={<Icon type="mail" />} />
                )}
            </FormItem>
            </Col>
          }
          {
            this.state.current === steps.length - 2
            &&
                <FormItem
                {...formItemLayout}
                  label="新邮箱"
                  hasFeedback
            >
            {getFieldDecorator('email', {
                  rules: [{
                            type: 'email', message: '输入邮箱的类型错误'
                  }, {
                            required: true, message: '请输入您的新邮箱'
                  },
                  {
                    validator: this.checkBinding
                  }]
                  })(
                    <Input   type="email" className="content_style" addonBefore={<Icon type="mail" />} />
                )}
            </FormItem>
          }
          {
            this.state.current === steps.length - 2
            &&
            <Row>
          <Col span="6" offset="9">
            <FormItem
            >
              {getFieldDecorator('imageCode', {
                rules: [{ required: true, message: '图片验证码不能为空!' },
                { min: 4, message: '图片验证码为4个字符' },
                { max: 4, message: '图片验证码为4个字符' }],
              })(
                <Input prefix={<Icon type="code-o" style={{ fontSize: 13 }} />} placeholder='请输入4位验证码,点击图片切换' style={{with:'100px'}}/>
                )}
            </FormItem>
          </Col>
          <Col span="4">
          <img className="image-code" src={this.state.captcha} onClick={this.changeImage.bind(this)} />
          </Col>
          <Col  span="6" offset="9">
            <FormItem
            >
              {getFieldDecorator('mailCode', {
              })(
                <Input  onChange={this.mailCodeChange.bind(this)} prefix={<Icon type="code-o" style={{ fontSize: 13 }} />} placeholder='请输入4位邮箱验证码'style={{with:'100px'}} />
                )}
            </FormItem>
          </Col>
          <Col span="4" >
          <Button className="btn-register" size="large"  loading={this.state.loading} loading={this.state.loading} disabled={this.state.disabledMailSend} htmlType='submit'>{this.state.sendcode}</Button>
          </Col>
        </Row>
          }
          {
            this.state.current ===2
            &&
            <Icon type="like" />
          }
        </div>
        <div className="steps-action">
          {
            this.state.current === steps.length - 3
            &&
            <Button type="primary" onClick={() => this.next()}>下一步</Button>
          }
          {
            this.state.current === steps.length - 2
            &&
            <Button type='submit' onClick={() => this.submit()}>完成</Button>  //完成步
          }
         {/*  {
            this.state.current === steps.length - 1
            &&
            <Button type="primary" onClick={() => message.success('Processing complete!')}>完成</Button>
          } */}
          {
            this.state.current > 0
            &&
            <Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>
              上一步
            </Button>
          }
        </div>
      </div>
      </Row>
      </Form>
    );
  }
}

const BindingForm = Form.create()(ManageForm);

export default class Binding extends React.Component {
  render() {
    return (
      <PanelBox>
        <div className="password-content">
          <BindingForm/>
        </div>
      </PanelBox>
    )
  }

}
